package org.ko.utils;

import java.io.IOException;
import java.util.Map;

import org.apache.http.HttpHost;
import org.apache.http.HttpVersion;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.ClientConnectionManager;
import org.apache.http.conn.HttpClientConnectionManager;
import org.apache.http.conn.params.ConnManagerParams;
import org.apache.http.conn.params.ConnRouteParams;
import org.apache.http.conn.scheme.PlainSocketFactory;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.scheme.SchemeRegistry;
import org.apache.http.conn.ssl.SSLSocketFactory;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.BasicResponseHandler;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.BasicHttpClientConnectionManager;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.apache.http.params.HttpProtocolParams;
import org.apache.http.protocol.HTTP;

import com.google.gson.JsonObject;

@SuppressWarnings("deprecation")
public class KOClient {

	/**
	 * 
	 * @param object----body数据模型
	 * @param header----存放的头信息
	 * @param uri-----请求url
	 * @param className-----需要返回的类型
	 * @return 返回值T
	 * @throws ClientProtocolException
	 * @throws IOException
	 */
	public static <T> T postClientBody (Object object, Map<String, String> header, String uri, Class<T> className) throws ClientProtocolException, IOException {
        ResponseHandler<String> responseHandler = new BasicResponseHandler();
        HttpClient httpClient = HttpClients.createDefault();
        HttpPost httpPost = new HttpPost(uri);
        
        String json = JSONConverter.objectToJson(object);
        StringEntity requestEntity = new StringEntity(json, "utf-8");

        requestEntity.setContentEncoding("utf-8");
        httpPost.setHeader("Content-type", "application/json");
        
        //保存头信息
//        if (MapUtils.isNotEmpty(header)) {
        	for (Map.Entry<String, String> entry : header.entrySet()) {
        		httpPost.setHeader(entry.getKey(), entry.getValue());
        	}
//        }
        
        httpPost.setEntity(requestEntity);
        String resultJson = httpClient.execute(httpPost, responseHandler);
        T result = JSONConverter.jsonToObject(resultJson, className);
        return result;
	}
	
	/**
	 * 发送json格式请求获取返回结果
	 * @param json
	 * @param uri
	 * @return
	 * @throws ClientProtocolException
	 * @throws IOException
	 */
	public String koClient (JsonObject json, String uri) throws ClientProtocolException, IOException {
         ResponseHandler<String> responseHandler = new BasicResponseHandler();
         HttpClient httpClient = HttpClients.createDefault();
         HttpPost httpPost = new HttpPost(uri);
         StringEntity requestEntity = new StringEntity(json.toString(), "utf-8");

         requestEntity.setContentEncoding("utf-8");

         httpPost.setHeader("Content-type", "application/json");
         httpPost.setEntity(requestEntity);
         return httpClient.execute(httpPost, responseHandler);
	}
	
	/**
	 * 获取代理httpclent对象
	 * @param host 网址
	 * @param port 端口
	 * @param userName 用户名
	 * @param password 密码
	 * @return
	 */
	public HttpClient getActClient(String host, Integer port, String userName, String password) {
	     //实例化对象
	     DefaultHttpClient httpClient = new DefaultHttpClient();
	     //添加url和端口号
	     AuthScope authScope = new AuthScope(host, port);
	     //用户名密码
	     UsernamePasswordCredentials upc = new UsernamePasswordCredentials(userName, password);

	     httpClient.getCredentialsProvider().setCredentials(authScope, upc);
	     HttpHost proxy = new HttpHost(host,port);
	     httpClient.getParams().setParameter(ConnRouteParams.DEFAULT_PROXY, proxy);
	     return httpClient;
	}
	
	/**
	 * httpclient对多线程的支持
	 * @return
	 */
	public HttpClient getHttpClient () {
		
		HttpParams params = new BasicHttpParams();
		// 设置一些基本参数
		HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
		HttpProtocolParams.setContentCharset(params, HTTP.UTF_8);
		HttpProtocolParams.setUseExpectContinue(params, true);
		HttpProtocolParams.setUserAgent(params, "Mozilla/5.0(Linux;U;Android 2.2.1;en-us;Nexus One Build.FRG83) "
				+ "AppleWebKit/553.1(KHTML,like Gecko) Version/4.0 Mobile Safari/533.1");
		//设置最大连接数
		ConnManagerParams.setMaxTotalConnections(params, 100);
		// 超时设置
		/* 从连接池中取连接的超时时间 */
		ConnManagerParams.setTimeout(params, 1000);
		/* 连接超时 */
		HttpConnectionParams.setConnectionTimeout(params, 2000);
		/* 请求超时 */
		HttpConnectionParams.setSoTimeout(params, 4000);

		// 设置我们的HttpClient支持HTTP和HTTPS两种模式
		SchemeRegistry schReg = new SchemeRegistry();
		schReg.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
		schReg.register(new Scheme("https", SSLSocketFactory.getSocketFactory(), 443));

		// 使用线程安全的连接管理来创建HttpClient
		ClientConnectionManager conMgr = new ThreadSafeClientConnManager(params, schReg);
		return new DefaultHttpClient(conMgr, params);
	}
	
	public static HttpClient getHttpClientv1 () {
		PoolingHttpClientConnectionManager connManager = new PoolingHttpClientConnectionManager();
		connManager.setMaxTotal(100);
		HttpClient client = HttpClients.createMinimal(connManager);
		return client;
	}
}
